
const tt = window["tt"];
import lzw = require('./lzw');
export default class Utils {
    static createUI(filepath: string, parent: cc.Node, callback: Function = null) {
        cc.loader.loadRes(filepath, cc.Prefab, (err, ret) => {
            var tmp: cc.Node = cc.instantiate(ret);
            tmp.parent = parent;
            if (callback) callback(tmp);
        })
    }

    public static getRandom(lower, upper): number {
        return Math.random() * (upper - lower) + lower;
    };

    public static getRandomInt(lower, upper): number {
        return Math.floor(Math.random() * (upper - lower)) + lower;
    };

    public static seed: number = 5;

    public static seedRandom(): number {
        return Utils.getRandom(0, 1);
        // this.seed = (this.seed * 9301 + 49297) % 233280;
        // return this.seed / 233280.0;
    }

    public static seedRandomInt(lower, upper): number {
        return Utils.getRandomInt(lower, upper);
        // return Math.floor(Utils.seedRandom() * (upper - lower)) + lower;
    }

    // function rand(number){
    //     
    // };

    private static rnd(seed) {
        seed = (seed * 9301 + 49297) % 233280; //为何使用这三个数?
        return seed / (233280.0);
    };

    public static formatNumber(num: number, afterdot: number = 1) {
        let res = "";
        let tempNum;
        let powNum;
        let unit = "";

        let areaArr = [];
        let unitArr = ["k", "m", "b", "aa", "ab", "ac", "ad", "ae", "af", "ag", "ah", "ai", "aj", "ak", "al", "am", "an", "ao", "ap", "aq", "ar", "as", "at",
            "au", "av", "aw", "ax", "ay", "az", "ba", "bb", "bc", "bd", "be", "bf", "bg", "bh", "bi", "bk", "bl", "bm", "bn", "bo", "bp", "bq", "br",
            "bs", "bt", "bu", "bv", "bw", "bx", "by", "bz", "ca", "cb", "cc", "cd", "ce", "cf", "cg", "ch", "ci", "cj", "ck", "cl", "cm", "cn"
        ];
        for (let i = 1; i < 69; i++) {
            let tmp = [];
            tmp.push(i * 3);
            tmp.push(i * 3 + 3);
            areaArr.push(tmp);
        }

        if (num < this.getPowNum(3)) {
            return num.toString();
        }
        for (let i = 0; i < areaArr.length; i++) {
            if (num >= this.getPowNum(areaArr[i][0]) && num < this.getPowNum(areaArr[i][1])) {
                powNum = areaArr[i][0];
                unit = unitArr[i];
                break;
            }
        }
        tempNum = num / this.getPowNum(powNum);
        if (afterdot == 2) {
            res = Math.floor(tempNum * 100) / 100 + unit;
        }
        else {
            res = Math.floor(tempNum * 10) / 10 + unit;
        }
        return res;
    };
    public static getPowNum(p) {
        return Math.pow(10, p);
    };

    public static deepCopy(obj) {
        var result = Array.isArray(obj) ? [] : {};
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                if (typeof obj[key] === 'object') {
                    result[key] = Utils.deepCopy(obj[key]);
                } else {
                    result[key] = obj[key];
                }
            }
        }
        return result;
    };

    public static setServerTime(time: number) {
        Utils.timeOffset = time - new Date().getTime();
        cc.log("timeOffset:", Utils.timeOffset)
    }

    public static timeOffset: number = 0;
    public static getServerTime() {
        return new Date().getTime() + Utils.timeOffset;
    }


    public static base64decode(input) {
        var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = this.utf8decode(output);
        return output;
    };

    public static utf8decode(utftext) {
        var string = "";
        var i = 0;
        var c = 0;
        var c2 = 0;
        var c3 = 0;
        while (i < utftext.length) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    };

    public static formatTime(second) {
        var hour = Math.floor(second / 60 / 60);
        var minute = Math.floor((second - hour * 3600) / 60);
        second = Math.floor(second % 60);
        var day = Math.floor(hour / 24);
        hour = hour % 24;

        var str = day ? (day < 10 ? "0" + day : day) + ":" : "";
        if (day) {
            str += (hour ? (hour < 10 ? "0" + hour : hour) : "00") + "";
        }
        else {
            str += (hour ? (hour < 10 ? "0" + hour : hour) : "") + "";
        }
        str += (minute ? (minute < 10 ? "0" + minute : minute) : "00") + ":";
        str += second ? (second < 10 ? "0" + second : second) : "00";
        return str;
    };

    public static addClickEvent(node, target, component, handler, customEventData) {
        var eventHandler = new cc.Component.EventHandler();
        eventHandler.target = target;
        eventHandler.component = component;
        eventHandler.handler = handler;
        if (customEventData) eventHandler.customEventData = customEventData;

        var clickEvents = node.getComponent(cc.Button).clickEvents;
        clickEvents.push(eventHandler);
    }

    public static printBones(bones: any) {
        console.log(bones.data.name)
        for (var i = 0; i < bones.children.length; ++i) {
            Utils.printBones(bones.children[i]);
        }
    }

    public static cloneObj(obj: any) {
        obj = JSON.stringify(obj);
        obj = JSON.parse(obj);
        return obj;
    }

    public static getTimeStrByS(second: number, longTime: boolean = false) {
        if (second < 0) second = 0;
        var h = Math.floor(second / 3600);
        second -= h * 3600;
        var m = Math.floor(second / 60);
        second -= m * 60;
        var front = "00";
        if (h > 9) {
            front = "" + h;
        } else {
            front = "0" + h;
        }
        var mid = "00";
        if (m > 9) {
            mid = "" + m;
        } else {
            mid = "0" + m;
        }
        var back = "00";
        if (second > 9) {
            back = "" + second;
        } else {
            back = "0" + second;
        }
        if (longTime) {
            return front + "：" + mid + "：" + back;
        } else {
            return mid + "：" + back;
        }
    }

    public static checkObjEmpty(obj: any) {
        if (obj) {
            for (var i in obj) {
                return false;
            }
            return true;
        } else {
            return true;
        }
    }

    
    public static DecompressStr(str: string): string {
        return lzw.lzw_decompress(str);
    }

    public static checkOrderOver(orderTime: number) {
        var date = new Date(orderTime);
        var dateNow = new Date(Utils.getServerTime());

        if (date.getFullYear() == dateNow.getFullYear() &&
            date.getMonth() == dateNow.getMonth() &&
            date.getDate() == dateNow.getDate()
        ) {
            return false;
        } else {
            return true;
        }
    }

    public static formatCoin(coin: number) {
        var str = "";
        if (coin >= 100000000) {
            str = (coin / 100000000).toFixed(2) + "亿";
        } else if (coin >= 10000) {
            str = (coin / 10000).toFixed(2) + "万";
        } else {
            str = "" + coin;
        }
        return str;
    }

    public static iosPurchaseVIP() {
        jsb.reflection.callStaticMethod("JSVC", "jsMethod");
    }

    public static getIOSID() {
        jsb.reflection.callStaticMethod("JSVC", "getID");
    }


    public static uploadUserData(data: any) {
        if (cc.sys.platform !== cc.sys.WECHAT_GAME) return;
        // 上传结果
        // 调用 uploadScore 云函数
        tt.cloud.callFunction({
            name: 'uploadUserData',
            // data 字段的值为传入云函数的第一个参数 event
            data: {
                data: data,
            },
            success: res => {
            },
            fail: err => {
                console.error('upload data failed', err)
            }
        });
    }

    public static getRankList(data: any) {
        if (cc.sys.platform !== cc.sys.WECHAT_GAME) return;
        // 上传结果
        // 调用 uploadScore 云函数
        tt.cloud.callFunction({
            name: 'getRankList',
            success: res => {
                console.log("getRankList:", res)
            },
            fail: err => {
                console.error('upload data failed', err)
            }
        });
    }


    public static setClipboardData(str) {
        if (!tt) return;
        tt.setClipboardData({
            data: str,
            success: (res) => {
                tt.getClipboardData({
                    success: (res) => {
                        tt.showToast({
                            title: '复制成功'
                        })
                    }
                })
            }
        })
    }

};